{% extends "student/base.html" %}

{% block title %}成绩分析{% endblock %}

{% block styles %}
<style>
  .analysis-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .semester-selector {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    padding: 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    border: 1px solid rgba(138, 215, 255, 0.3);
  }

  .semester-selector select {
    padding: 10px 20px;
    border: 2px solid rgba(138, 215, 255, 0.5);
    border-radius: 10px;
    font-size: 14px;
    color: #2c3e50;
    background: white;
    cursor: pointer;
    transition: all 0.3s ease;
    min-width: 180px;
    appearance: none;
    background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23399CDE' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 10px center;
    background-size: 16px;
  }

  .semester-selector select:hover {
    border-color: #399CDE;
    box-shadow: 0 0 0 3px rgba(57, 156, 222, 0.1);
  }

  .semester-selector select:focus {
    outline: none;
    border-color: #399CDE;
    box-shadow: 0 0 0 3px rgba(57, 156, 222, 0.2);
  }

  .semester-selector label {
    font-size: 15px;
    color: #2c3e50;
    font-weight: 500;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }

  .stat-card {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    padding: 25px;
    text-align: center;
    transition: all 0.3s ease;
  }

  .stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }

  .stat-value {
    font-size: 32px;
    font-weight: bold;
    color: #1976D2;
    margin: 10px 0;
  }

  .stat-label {
    color: #666;
    font-size: 14px;
  }

  .chart-container {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    padding: 25px;
    margin-bottom: 20px;
    transition: all 0.3s ease;
    height: 400px;
    display: flex;
    flex-direction: column;
  }

  .chart-container:hover {
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }

  .chart-title {
    font-size: 18px;
    color: #2c3e50;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
  }

  .chart-title i {
    color: #1976D2;
    font-size: 20px;
  }

  .chart-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
    gap: 25px;
    margin-bottom: 25px;
  }

  .chart-wrapper {
    flex: 1;
    position: relative;
    min-height: 300px;
  }

  .loading {
    display: none;
    text-align: center;
    padding: 20px;
  }

  .loading.active {
    display: block;
  }

  .loading-spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #1976D2;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 0 auto;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  /* 自定义图表样式 */
  .chart-container canvas {
    max-height: 300px;
    width: 100% !important;
  }
</style>
{% endblock %}

{% block content %}
<div class="analysis-container">
  <div class="semester-selector">
    <label for="semester">选择学期：</label>
    <select id="semester" onchange="updateCharts()">
      <option value="">全部学期</option>
      {% for semester in semester_labels %}
      <option value="{{ semester }}">{{ semester }}</option>
      {% endfor %}
    </select>
  </div>

  <div class="stats-grid">
    <div class="stat-card">
      <div class="stat-label">平均分</div>
      <div class="stat-value">{{ average_grade|default('0') }}</div>
    </div>
    <div class="stat-card">
      <div class="stat-label">最高分</div>
      <div class="stat-value">{{ highest_grade|default('0') }}</div>
    </div>
    <div class="stat-card">
      <div class="stat-label">最低分</div>
      <div class="stat-value">{{ lowest_grade|default('0') }}</div>
    </div>
    <div class="stat-card">
      <div class="stat-label">课程数</div>
      <div class="stat-value">{{ course_count|default('0') }}</div>
    </div>
  </div>

  <div class="chart-grid">
    <div class="chart-container">
      <h3 class="chart-title">
        <i class="fas fa-chart-pie"></i>
        成绩分布
      </h3>
      <div class="chart-wrapper">
        <canvas id="gradeDistribution"></canvas>
      </div>
    </div>
    <div class="chart-container">
      <h3 class="chart-title">
        <i class="fas fa-chart-line"></i>
        课程成绩对比
      </h3>
      <div class="chart-wrapper">
        <canvas id="courseComparison"></canvas>
      </div>
    </div>
  </div>

  <div class="chart-grid">
    <div class="chart-container">
      <h3 class="chart-title">
        <i class="fas fa-chart-bar"></i>
        成绩趋势
      </h3>
      <div class="chart-wrapper">
        <canvas id="gradeTrend"></canvas>
      </div>
    </div>
  </div>
</div>

<!-- 将数据存储在隐藏的div中 -->
<div id="chartData" style="display: none;" data-grade-distribution='{{ grade_distribution|tojson|safe }}'
  data-course-names='{{ course_names|tojson|safe }}' data-course-grades='{{ course_grades|tojson|safe }}'
  data-semester-labels='{{ semester_labels|tojson|safe }}' data-semester-averages='{{ semester_averages|tojson|safe }}'
  data-all-grades='{{ all_grades|tojson|safe }}'>
</div>
{% endblock %}

{% block scripts %}
<script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<script>
  let gradeDistributionChart, courseComparisonChart, gradeTrendChart;

  document.addEventListener('DOMContentLoaded', function () {
    // 从隐藏的div中获取数据
    const chartData = document.getElementById('chartData');
    const gradeDistributionData = JSON.parse(chartData.dataset.gradeDistribution);
    const courseNames = JSON.parse(chartData.dataset.courseNames);
    const courseGrades = JSON.parse(chartData.dataset.courseGrades);
    const semesterLabels = JSON.parse(chartData.dataset.semesterLabels);
    const semesterAverages = JSON.parse(chartData.dataset.semesterAverages);
    const allGrades = JSON.parse(chartData.dataset.allGrades);

    // 初始化图表
    initializeCharts(gradeDistributionData, courseNames, courseGrades, semesterLabels, semesterAverages);

    // 添加学期选择器的change事件监听器
    document.getElementById('semester').addEventListener('change', updateCharts);
  });

  function initializeCharts(gradeDistributionData, courseNames, courseGrades, semesterLabels, semesterAverages) {
    // 成绩分布图
    gradeDistributionChart = new Chart(document.getElementById('gradeDistribution'), {
      type: 'pie',
      data: {
        labels: ['90-100分', '80-89分', '70-79分', '60-69分', '60分以下'],
        datasets: [{
          data: gradeDistributionData,
          backgroundColor: [
            '#255E98',  // 37, 94, 152
            '#257DD4',  // 37, 125, 212
            '#FDAC00',  // 253, 172, 0
            '#8AD7FF',  // 138, 215, 255
            'rgba(37, 94, 152, 0.2)'  // 深色透明版
          ],
          borderWidth: 0,
          hoverOffset: 4
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'right',
            labels: {
              padding: 20,
              font: {
                size: 12,
                family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"
              }
            }
          },
          tooltip: {
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            titleColor: '#2c3e50',
            bodyColor: '#2c3e50',
            borderColor: 'rgba(138, 215, 255, 0.3)',
            borderWidth: 1,
            padding: 12,
            boxPadding: 6,
            usePointStyle: true
          }
        }
      }
    });

    // 课程成绩对比图
    courseComparisonChart = new Chart(document.getElementById('courseComparison'), {
      type: 'bar',
      data: {
        labels: courseNames,
        datasets: [{
          label: '成绩',
          data: courseGrades,
          backgroundColor: courseGrades.map((_, index) =>
            index % 2 === 0 ? '#399CDE' : '#265E98'
          ),
          borderRadius: 6,
          borderSkipped: false,
          hoverBackgroundColor: courseGrades.map((_, index) =>
            index % 2 === 0 ? '#8AD7FF' : '#FDAC00'
          )
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            titleColor: '#2c3e50',
            bodyColor: '#2c3e50',
            borderColor: 'rgba(138, 215, 255, 0.3)',
            borderWidth: 1,
            padding: 12,
            boxPadding: 6
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            max: 100,
            grid: {
              color: 'rgba(138, 215, 255, 0.1)'
            },
            ticks: {
              font: {
                size: 12,
                family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"
              }
            }
          },
          x: {
            grid: {
              display: false
            },
            ticks: {
              font: {
                size: 12,
                family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"
              }
            }
          }
        }
      }
    });

    // 成绩趋势图
    gradeTrendChart = new Chart(document.getElementById('gradeTrend'), {
      type: 'line',
      data: {
        labels: semesterLabels,
        datasets: [{
          label: '平均分',
          data: semesterAverages,
          borderColor: '#1976D2',  // 更深的蓝色
          backgroundColor: 'rgba(25, 118, 210, 0.15)',  // 更明显的填充色
          tension: 0.3,  // 减小曲线张力，使趋势更明显
          fill: true,
          pointBackgroundColor: '#1976D2',
          pointBorderColor: '#fff',
          pointBorderWidth: 3,  // 增加点的大小
          pointRadius: 6,  // 增加点的大小
          pointHoverRadius: 8,  // 增加悬停时点的大小
          borderWidth: 3,  // 增加线条宽度
          pointStyle: 'circle',  // 使用圆形点
          borderColor: function (context) {
            const index = context.dataIndex;
            const value = context.dataset.data[index];
            const nextValue = context.dataset.data[index + 1];
            if (nextValue === undefined) return '#1976D2';
            return value < nextValue ? '#4CAF50' : value > nextValue ? '#F44336' : '#1976D2';
          }
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            titleColor: '#2c3e50',
            bodyColor: '#2c3e50',
            borderColor: 'rgba(25, 118, 210, 0.3)',
            borderWidth: 2,
            padding: 15,
            boxPadding: 8,
            callbacks: {
              label: function (context) {
                const value = context.parsed.y;
                const index = context.dataIndex;
                const nextValue = context.dataset.data[index + 1];
                let trend = '';
                if (nextValue !== undefined) {
                  const diff = nextValue - value;
                  trend = diff > 0 ? '↑' : diff < 0 ? '↓' : '→';
                  trend += ` ${Math.abs(diff).toFixed(2)}分`;
                }
                return `平均分: ${value.toFixed(2)} ${trend}`;
              }
            }
          }
        },
        scales: {
          y: {
            beginAtZero: false,  // 不从0开始，更好地显示变化
            min: Math.min(...semesterAverages) - 5,  // 最小值比最低分低5分
            max: Math.max(...semesterAverages) + 5,  // 最大值比最高分高5分
            grid: {
              color: 'rgba(138, 215, 255, 0.2)',  // 更明显的网格线
              drawBorder: true,
              borderDash: [5, 5]  // 虚线网格
            },
            ticks: {
              font: {
                size: 12,
                weight: 'bold',  // 加粗刻度值
                family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"
              },
              padding: 10,
              callback: function (value) {
                return value.toFixed(1) + '分';  // 添加"分"单位
              }
            }
          },
          x: {
            grid: {
              display: false
            },
            ticks: {
              font: {
                size: 12,
                weight: 'bold',  // 加粗刻度值
                family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"
              },
              padding: 10
            }
          }
        },
        interaction: {
          intersect: false,  // 鼠标悬停时显示最近的点
          mode: 'index'
        },
        animation: {
          duration: 2000,  // 增加动画时长
          easing: 'easeInOutQuart'  // 使用更平滑的动画效果
        }
      }
    });
  }

  function updateCharts() {
    const semester = document.getElementById('semester').value;
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'loading active';
    loadingDiv.innerHTML = '<div class="loading-spinner"></div>';
    document.querySelector('.analysis-container').appendChild(loadingDiv);

    // 获取选中学期的数据
    fetch(`/student/api/grades?semester=${semester}`)
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        if (!data || data.length === 0) {
          throw new Error('No data available');
        }
        // 更新统计数据
        updateStats(data);
        // 更新图表
        updateChartsData(data);
        // 移除加载动画
        loadingDiv.remove();
      })
      .catch(error => {
        console.error('Error:', error);
        loadingDiv.remove();
        alert('获取数据失败，请稍后重试');
      });
  }

  function updateStats(data) {
    try {
      // 计算统计数据
      const grades = data.map(g => g.total_score);
      const average = grades.reduce((a, b) => a + b, 0) / grades.length || 0;
      const highest = Math.max(...grades) || 0;
      const lowest = Math.min(...grades) || 0;
      const count = grades.length;

      // 更新显示
      const statValues = document.querySelectorAll('.stat-value');
      if (statValues.length >= 4) {
        statValues[0].textContent = average.toFixed(2);
        statValues[1].textContent = highest.toFixed(2);
        statValues[2].textContent = lowest.toFixed(2);
        statValues[3].textContent = count;
      } else {
        console.error('Could not find all stat value elements');
      }
    } catch (error) {
      console.error('Error updating stats:', error);
    }
  }

  function updateChartsData(data) {
    try {
      // 更新成绩分布
      const distribution = calculateGradeDistribution(data);
      if (gradeDistributionChart) {
        gradeDistributionChart.data.datasets[0].data = distribution;
        gradeDistributionChart.update();
      }

      // 更新课程成绩对比
      const courseData = data.map(g => ({
        name: g.course_name,
        grade: g.total_score
      }));
      if (courseComparisonChart) {
        courseComparisonChart.data.labels = courseData.map(c => c.name);
        courseComparisonChart.data.datasets[0].data = courseData.map(c => c.grade);
        courseComparisonChart.update();
      }
    } catch (error) {
      console.error('Error updating charts:', error);
    }
  }

  function calculateGradeDistribution(grades) {
    const distribution = [0, 0, 0, 0, 0];
    grades.forEach(grade => {
      const score = grade.total_score;
      if (score >= 90) distribution[0]++;
      else if (score >= 80) distribution[1]++;
      else if (score >= 70) distribution[2]++;
      else if (score >= 60) distribution[3]++;
      else distribution[4]++;
    });
    return distribution;
  }
</script>
{% endblock %}